package com.cy.interfacetest.proxy;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.reflect.TypeUtils;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

public class ModuleProxy<T> {
    private static final String TAG = "ModuleProxy";
    private String content = "";

    public void setLog(StringBuilder sb) {
        sb.delete(0, sb.length());
        sb.append(content);
    }

    /**
     * 代理接口实例
     *
     * @param target
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public T getInstance(T target) {

        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), (Object proxy, Method method, Object[] args) -> {
            Object result = null;
            String methodName = method.getName();
            try {
                StringBuffer strArgs = new StringBuffer();
                //todo 判断无参方法
                if (Optional.ofNullable(args).isPresent()) {
                    Arrays.stream(args).forEach(e -> {
                        // TODO: 2023/8/14  判断不是数组，简单转化，否则就按照数组
                        if (!Objects.isNull(e)) {
                            if (!TypeUtils.isArrayType(e.getClass())) {
                                strArgs.append(ConvertUtils.convert(e, e.getClass()));

                            } else {
                                strArgs.append(" : " + Arrays.toString((String[]) e));
                            }
                        }

                    });
                }

                Log.i(TAG, methodName + " :参数 = " + strArgs.toString());
                content = methodName + " :参数 = " + strArgs.toString();// TODO: 2024/11/7 把日志输出给组件
                result = method.invoke(target, args);
                // Perform additional logic after method invocation
                // TODO: 2023/8/8 Based on the result, it should be either "red" or "green"
                if (result instanceof Boolean) {
                    if ((Boolean) result) {
                        Log.i(TAG, methodName + ".Pass");
                    } else {
                        Log.i(TAG, methodName + ".Failure");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        });
    }
}
